<?php
namespace app\common\logic;
use think\Cache;
use think\Config;

class Wework
{
    public static $objects = [];
    public static $errCode = 0;

    public static $baseUrl = 'https://qyapi.weixin.qq.com/';

    public static function init()
    {
        import('weworkapi_php-master/api/src/CorpAPI', EXTEND_PATH, '.class.php');
        import('weworkapi_php-master/callback/xmlparse', EXTEND_PATH, '.php');
        import('weworkapi_php-master/callback/WXBizMsgCrypt', EXTEND_PATH, '.php');
        import('weworkapi_php-master/api/src/ServiceCorpAPI', EXTEND_PATH, '.class.php');
    }


    //消息解密类
    //第三方应用的消息解密 第三个参数为 SuiteID（应用id）
    //消息解密方法
    public static function decodeXml($msgSig,$stamp,$nonce,$regData)
    {
        self::init();
        $encodingAesKey = config('wework.EncodingAESKey');
        $token = config('wework.Token');


        $token_id = config('wework.corpId');
        self::$objects['WXBizMsgCrypt'] = new \WXBizMsgCrypt($token,$encodingAesKey,$token_id);

        // 解析之后的明文-xml结果
        $xml = "";
        $errCode = self::$objects['WXBizMsgCrypt']->DecryptMsg($msgSig, $stamp, $nonce, $regData, $xml);

        if ($errCode == 0) {
            self::$errCode = 0;
            return toXml($xml);
        } else {
            self::$errCode = $errCode;
            return '消息解密失败';
        }
    }



    public static function decodeUrl($msgSig,$stamp,$nonce,$echostr)
    {

        self::init();
        $encodingAesKey = config('wework.EncodingAESKey');
        $token = config('wework.Token');


        $token_id = config('wework.corpId');
        self::$objects['WXBizMsgCrypt'] = new \WXBizMsgCrypt($token,$encodingAesKey,$token_id);

        // 解析之后的明文-xml结果
        $data = "";
        $errCode = self::$objects['WXBizMsgCrypt']->VerifyURL($msgSig, $stamp, $nonce, $echostr, $data);

        if ($errCode == 0) {
            self::$errCode = 0;
            return $data;
        } else {
            self::$errCode = $errCode;
            return '消息解密失败';
        }
    }



    /**
     * 获取学生或家长信息
     * $accessToken 为 授权企业的asscee_token
     * @param $user_id
     * @return mixed
     */
    public static function schoolUserGet($user_id)
    {
        $access_token = self::getAccessToken();
logs($access_token,'tokenss');
        $_res = \fast\Http::get(self::$baseUrl."cgi-bin//school/user/get?access_token={$access_token}&userid={$user_id}");
        $res = json_decode($_res,true);
        return $res;
    }


    /**
     * 获取部门列表-家校通讯录
     * $accessToken 为 授权企业的asscee_token
     * @param $user_id
     * @return mixed
     *
     * https://qyapi.weixin.qq.com/cgi-bin/school/department/list?access_token=ACCESS_TOKEN&id=ID
     */
    public static function schoolDepartmentGet($accessToken,$department_id = '')
    {
        $_res = \fast\Http::get(self::$baseUrl."cgi-bin/school/department/list?access_token={$accessToken}&id={$department_id}");
        $res = json_decode($_res,true);
        return $res;
    }


    /**
     * 获取部门列表-通讯录
     * $accessToken 为 授权企业的asscee_token
     * @param $user_id
     * @return mixed
     *
     * https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=ACCESS_TOKEN&id=ID
     */
    public static function departmentListGet($accessToken,$department_id = '')
    {
        $_res = \fast\Http::get(self::$baseUrl."cgi-bin/department/list?access_token={$accessToken}&id={$department_id}");
        $res = json_decode($_res,true);
        return $res;
    }



    /**
     * 获取通讯录成员-通讯录
     * @param $accessToken
     * @param $department_id 部门ID
     * @return mixed
     * https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=FETCH_CHILD
     * https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=FETCH_CHILD
     * https://qyapi.weixin.qq.com/cgi-bin/school/user/simplelist?access_token=aT6tps8dHjOHhjTIX2_nXSGJuVpXrQx4pFK7SSow06iIGkLhFGOcgSRpqGCSlWbxuenwDQJYAhlE4TjgQsbvwMGYO2UCmtyIsD9cSP-p-kwCCXUXrFKhf8bmUkmMcD0igzCzzdbSCnXCEqHjJpwYGx1WvxA62uS7mt8TU3RW5fRWrb2iyj4wq8xHedrcXrWPp5nX6OT226L2Bvn_kSD-AA&department_id=1
     */
    public static function departmenUserListGet($accessToken,$department_id)
    {
        $echo = self::$baseUrl."cgi-bin/user/simplelist?access_token={$accessToken}&department_id={$department_id}";
        $_res = \fast\Http::get($echo);
        $res = json_decode($_res,true);
        return $res;
    }



    /**
     * 获取通讯录部门成员-非家校通讯录
     * @param $accessToken
     * @param $department_id 部门ID
     * @return mixed
     */
    public static function userListGet($accessToken,$department_id)
    {
        $_res = \fast\Http::get(self::$baseUrl."cgi-bin/user/list?access_token={$accessToken}&department_id={$department_id}");
        $res = json_decode($_res,true);
        return $res;
    }


    /**
     * 获取通讯录成员-家校通讯录
     * @param $accessToken
     * @param $department_id 部门ID
     * @return mixed
     */
    public static function schoolUserListGet($accessToken,$department_id)
    {
        $_res = \fast\Http::get(self::$baseUrl."cgi-bin/school/user/list?access_token={$accessToken}&department_id={$department_id}");
        $res = json_decode($_res,true);
        return $res;
    }








    /**
     * 获取企业授权码
     */
    public static function getAuthCode($temp_auth_code)
    {
        if (!isset(self::$objects['ServiceCorpAPI'])) {
            self::init();
            $encodingAesKey = config('wework.EncodingAESKey');
            $SuiteIDSecret = config('wework.SuiteIDSecret');
            $SuiteID = config('wework.SuiteID');
            self::$objects['ServiceCorpAPI'] = new \ServiceCorpAPI($SuiteID,$SuiteIDSecret,cache('suite_ticket'));
        }

        $res = self::$objects['ServiceCorpAPI']->GetPermanentCode($temp_auth_code);

        return $res;

    }



    //获取应用accesstoken
    public static function getAccessToken()
    {
        if (!Cache::has('access_token')) {
            $config = config('wework');
            $res = self::refreshAccessToken($config['corpId'],$config['AppSecret']);
            if (isset($res['access_token'])) {
                Cache::set('access_token',$res['access_token'],($res['expires_in'] - 1));
                return $res['access_token'];
            }

            throw new \Exception('获取 accessToken 失败');
        }else{
            return Cache::get('access_token');
        }
    }



    /**
     * 获取指定应用的accesstoken
     * @return [type] [description]
     */
    public static function getAppAccessToken($appname)
    {
        if (!Cache::has("{$appname}_access_token")) {
            $config = config("wework.{$appname}");
            $res = self::refreshAccessToken($config['corpId'],$config['Secret']);
            if (isset($res['access_token'])) {
                Cache::set("{$appname}_access_token",$res['access_token'],($res['expires_in'] - 1));
                return $res['access_token'];
            }
            throw new \Exception('获取 accessToken 失败');
        }else{
            return Cache::get("{$appname}_access_token");
        }
    }



    //获取通讯录accesstoken
    public static function getBookAccessToken()
    {
        if (!Cache::has('book_access_token')) {
            $config = config('wework');
            $res = self::refreshAccessToken($config['corpId'],$config['AppSecret_book']);
            if (isset($res['access_token'])) {
                Cache::set('book_access_token',$res['access_token'],($res['expires_in'] - 1));
                return $res['access_token'];
            }

            throw new \Exception('获取 accessToken 失败');
        }else{
            return Cache::get('book_access_token');
        }
    }

    /**
     * 刷新授权企业的 access_token
     * @param  [type] $corpid         [企业ID]
     * @param  [type] $permanent_code [应用的凭证密钥]
     * @return [type]                 [description]
     */
    public static function refreshAccessToken($corpid,$permanent_code)
    {
        //<!-->
        /*$suite_access_token = self::getSuiteAccessToken();
        $_res = \fast\Http::post(self::$baseUrl."cgi-bin/service/get_corp_token?suite_access_token={$suite_access_token}",json_encode([
            'auth_corpid'      => $corpid,
            'permanent_code'   => $permanent_code,
        ]));*/

        $_res = \fast\Http::get(self::$baseUrl."cgi-bin/gettoken?corpid={$corpid}&corpsecret={$permanent_code}");

        $res = json_decode($_res,true);
        return $res;

    }


    /**
     * 应获取用的 suite_access_token
     */
    public static function getSuiteAccessToken()
    {
        $suite_access_token = cache('suite_access_token');
        if ($suite_access_token) {
            logs('拿存在的:'.$suite_access_token);
            return $suite_access_token;
        }else{
            $_res = \fast\Http::post(self::$baseUrl."cgi-bin/service/get_suite_token",json_encode([
                'suite_id'      => config('wework.SuiteID'),
                'suite_secret'  => config('wework.SuiteIDSecret'),
                'suite_ticket'  => cache('suite_ticket')
            ]));

            logs($_res,'获取新的 suite_access_token');

            $res = json_decode($_res,true);
            cache('suite_access_token',$res['suite_access_token'],['expire'=>$res['expires_in']]);
            logs('获取新的:'.$suite_access_token);

            return $res['suite_access_token'];
        }
    }


    /**
     * 获取访问用户的身份
     * @return mixed
     *https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE
     */
    public static function getuserinfo3rd($code)
    {
        $access_token = self::getAccessToken();
        $_res = \fast\Http::get(self::$baseUrl."cgi-bin/user/getuserinfo?access_token={$access_token}&code={$code}");
        $res = json_decode($_res,true);
        return $res;
    }


    /**
     * 获取外部联系人详情(针对外部访问的家长)
     * @param  [type] $code [description]
     * @return [type]       [description]
     * https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=ACCESS_TOKEN&external_userid=EXTERNAL_USERID
     */
    public static function externalcontact($external_userid)
    {
        $access_token = self::getAccessToken();
        $_res = \fast\Http::get(self::$baseUrl."cgi-bin/externalcontact/get?access_token={$access_token}&external_userid={$external_userid}");
        $res = json_decode($_res,true);
        return $res;
    }



    /**
     * 读取成员（针对内部访问的老师）
     * @param  [type] $external_userid [description]
     * @return [type]                  [description]
     * https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID
     */
    public static function getUser($userid)
    {
        $access_token = self::getAccessToken();
        $_res = \fast\Http::get(self::$baseUrl."cgi-bin/user/get?access_token={$access_token}&userid={$userid}");
        $res = json_decode($_res,true);
        return $res;
    }

    //同步部门成员-获取成员详情（非家校通讯录）
    public static function getUserInfo($accessToken,$userid)
    {
        $_res = \fast\Http::get(self::$baseUrl."cgi-bin/user/get?access_token={$accessToken}&userid={$userid}");
        $res = json_decode($_res,true);
        return $res;
    }





    /**
     * 上传临时素材
     */
    public static function upload($access_token,$type,$file)
    {
        $suite_access_token = self::getSuiteAccessToken();
        $_res = \fast\Http::post(self::$baseUrl."cgi-bin/media/upload?access_token={$access_token}&type={$type}&debug=1",$file);

        $res = json_decode($_res,true);
        return $res;
    }


    //删除学生
    public static function deleteStudent($access_token,$userid)
    {
        $suite_access_token = self::getSuiteAccessToken();
        $_res = \fast\Http::get(self::$baseUrl."cgi-bin/school/user/delete_student?access_token={$access_token}&userid={$userid}&debug=1");

        $res = json_decode($_res,true);
        return $res;
    }


    //删除家长
    public static function deleteParent($access_token,$userid)
    {
        https://qyapi.weixin.qq.com/cgi-bin/school/user/delete_parent?access_token=ACCESS_TOKEN&userid=USERID
        $suite_access_token = self::getSuiteAccessToken();
        $_res = \fast\Http::get(self::$baseUrl."cgi-bin/school/user/delete_parent?access_token={$access_token}&useride={$userid}&debug=1");

        $res = json_decode($_res,true);
        return $res;
    }



}